package com.lzq.concurrent.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ThenRunMain {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 线程异步执行任务");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "execute result";
        });

        CompletableFuture<Void> voidCompletableFuture = future.thenRun(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " 执行任务后需要再执行额外任务 - 前");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 执行任务后需要再执行额外任务 - 后");
            }
        });

        // get 会阻塞到 future 的return, 但不理会 thenRun() 有没有执行完成
        String result = future.get();
        System.out.println(Thread.currentThread().getName() + " 执行结果: " + result);

        voidCompletableFuture.get(); // 则会等到 thenRun() 执行完毕

    }

}
